package gl.java.umsp.gateway;

import gl.java.umsp.Umsp;
import gl.java.umsp.bean.ErrMsg;
import gl.java.umsp.bean.MatchResult;
import gl.java.umsp.event.Event;
import gl.java.umsp.event.EventPublisher;
import gl.java.umsp.event.EventSubscriber;
import gl.java.umsp.event.IEventSubscriber;
import gl.java.umsp.router.ChannelRouter;
import gl.java.util.JsonUtil;
import io.netty.channel.Channel;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

import java.util.Observable;
import java.util.Observer;

@Slf4j
public class InnerServiceEventHandler implements IEventSubscriber {
    private InnerServiceEventHandler() {
    }

    private static class SingleHolder {
        final static InnerServiceEventHandler holder = new InnerServiceEventHandler();
    }

    public static InnerServiceEventHandler getInstance() {
        return InnerServiceEventHandler.SingleHolder.holder;
    }

    @Override
    public void onMessage(String channel, String message) {
        try {
            if (Event.CHANNEL_MATCH_EVENT_RESULT.equals(channel)) {
                MatchResult result = JsonUtil.fromJson(message, MatchResult.class);
                Channel connectionChannel = null;
                if (result.wantToMatchUser != null) {
                    connectionChannel = ChannelRouter.getInstance().getChannel(result.wantToMatchUser.userID);
                }
                if (connectionChannel != null) {
                    Umsp.returnStringMsg(Umsp.CMD_MATCH_RSP, message,
                            connectionChannel);
                } else {
                    log.warn(result.wantToMatchUser + " has offline");
                }

            } else if (Event.ERR.equals(channel)) {//处理错误消息
                ErrMsg msg = JsonUtil.fromJson(message, ErrMsg.class);
                Umsp.returnErrMsg(Umsp.CMD_MSG, msg.getErrCode(), msg.getErrString(),
                        ChannelRouter.getInstance().getChannel(msg.getUserID()));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

    }
}
